package org.jeecg.modules.rental.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.boot.starter.lock.client.RedissonLockClient;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.iot.api.IControlAPI;
import org.jeecg.modules.iot.cache.EBikeCache;
import org.jeecg.modules.iot.model.FieldStatus;
import org.jeecg.modules.iot.model.control.CentralControlConfig;
import org.jeecg.modules.iot.model.control.SpeedOtherConfig;
import org.jeecg.modules.rental.entity.RentalAccountPackage;
import org.jeecg.modules.rental.entity.RentalEBike;
import org.jeecg.modules.rental.mapper.RentalAccountMapper;
import org.jeecg.modules.rental.mapper.RentalEBikeMapper;
import org.jeecg.modules.rental.req.MoveCarReq;
import org.jeecg.modules.rental.req.RentalManageCarReq;
import org.jeecg.modules.rental.service.IEquService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Api(tags="客户端设备信息")
@RestController
@RequestMapping("/ctrl/equ")
@Slf4j
public class EquController {

    @Autowired
    private IEquService equService;
    @Resource
    private RedissonLockClient redissonLockClient;
    @Resource
    private RentalEBikeMapper rentalCarMapper;
    @Resource
    private RentalAccountMapper rentalPayAccountMapper;
    @Autowired
    private IControlAPI iControlAPI;

    @Autowired
    private EBikeCache vehicleCache;

    @PostMapping("/e-bike/on")
    @ApiOperation("上电")
    public Result powerOn(){
        return Result.OK("equ.poweron.success", equService.powerOn());
    }

    @PostMapping("/e-bike/off")
    @ApiOperation("断电")
    public Result powerOff(){
        return Result.OK("equ.poweroff.success", equService.powerOff());
    }

    @PostMapping("/e-bike/locked")
    @ApiOperation("设防")
    public Result locked(){
        return Result.OK("equ.defense.success", equService.locked());
    }

    @PostMapping("/e-bike/unlock")
    @ApiOperation("撤防")
    public Result unlock(){
        return Result.OK("equ.disarming.success", equService.unlock());
    }

    @PostMapping("/e-bike/search")
    @ApiOperation("寻车")
    public Result search(){
        return Result.OK("寻车成功", equService.search());
    }

    @PostMapping("/e-bike/unlock-seat")
    @ApiOperation("座位锁")
    public Result unlockSeat(){
        return Result.OK("打开座位锁", equService.unlockSeat());
    }


    @PostMapping("/e-bike/enableSportMode")
    @ApiOperation("开启运动模式")
    public Result enableSportMode(@RequestBody RentalManageCarReq rentalManageCar) {
        try {
            // 调用 IControlAPI 中的开启运动模式方法
            boolean isSuccess = equService.enableSportMode(rentalManageCar.getEnable());

            if (isSuccess) {
                return Result.OK("运动模式开启成功");
            } else {
                return Result.error("运动模式开启失败");
            }
        } catch (Exception e) {
            log.error("开启运动模式失败", e);
            return Result.error("开启运动模式失败：" + e.getMessage());
        }
    }


    @PostMapping("/e-bike/manage/enableSportMode")
    @ApiOperation("开启运动模式")
    public Result enableManageSportMode(@RequestBody RentalManageCarReq rentalManageCar) {
        try {
            // 调用 IControlAPI 中的开启运动模式方法
            boolean isSuccess = equService.enableManageSportMode(rentalManageCar.getEnable(),rentalManageCar.getCarId());

            if (isSuccess) {
                return Result.OK("运动模式开启成功");
            } else {
                return Result.error("运动模式开启失败");
            }
        } catch (Exception e) {
            log.error("开启运动模式失败", e);
            return Result.error("开启运动模式失败：" + e.getMessage());
        }
    }


    @GetMapping("/e-bike/getSportModeStatus") // 使用 GetMapping，因为是查询操作
    @ApiOperation("获取运动模式状态")
    public Result<Boolean> getSportModeStatus(@RequestParam(name = "terminalId") String terminalId, @RequestParam(name = "phone") String phone) {
        try {
            RentalEBike car=new RentalEBike();
            car.setPhone(phone);
            car.setCarCode(terminalId);
            // 调用 equService 中的获取运动模式状态方法
            boolean isSportModeEnabled = equService.getSportModeStatus(car); //  假设 equService 中有这个方法
            return Result.OK(isSportModeEnabled); // 直接返回布尔值
        } catch (Exception e) {
            log.error("获取运动模式状态失败", e);
            return Result.error("获取运动模式状态失败：" + e.getMessage());
        }
    }


    @PostMapping("/car/on")
    @ApiOperation("上电")
    public Result carPowerOn(@RequestBody RentalAccountPackage rentalAccountPackage){
        return Result.OK("equ.poweron.success",equService.openCar(rentalAccountPackage));
    }

    @PostMapping("/car/manage/on")
    @ApiOperation("上电(管理员)")
    public Result carManagePowerOn(@RequestBody RentalManageCarReq rentalManageCar){
        return Result.OK("equ.poweron.success",equService.openManageCar(rentalManageCar.getCarId()));
    }

    @PostMapping("/car/off")
    @ApiOperation("断电")
    public Result carPowerOff(@RequestBody RentalAccountPackage rentalAccountPackage){
        return Result.OK("equ.poweroff.success",equService.closeCar(rentalAccountPackage));
    }

    @PostMapping("/car/revertAudio")
    @ApiOperation("还车")
    public Result carRevert(@RequestBody RentalAccountPackage rentalAccountPackage){
        return Result.OK( equService.setPlayAudio(rentalAccountPackage.getCarId(), (byte) 10));
    }

    @PostMapping("/car/manage/off")
    @ApiOperation("断电(管理员)")
    public Result carPowerOff(@RequestBody RentalManageCarReq rentalManageCar ){
        return Result.OK("equ.poweroff.success",equService.closeManageCar(rentalManageCar.getCarId()));
    }

    @PostMapping("/defensive/measures")
    @ApiOperation("设防")
    public Result defensiveMeasures(@RequestBody RentalAccountPackage rentalAccountPackage){
        return Result.OK("equ.defense.success",equService.defenseCar(rentalAccountPackage));
    }

    @PostMapping("/defensive/manage/measures")
    @ApiOperation("设防(管理员)")
    public Result defensiveManageMeasures(@RequestBody RentalManageCarReq rentalManageCar){
        return Result.OK("equ.defense.success",equService.defenseManageCar(rentalManageCar.getCarId()));
    }

    @PostMapping("/defensive/disarming")
    @ApiOperation("撤防")
    public Result disarming(@RequestBody RentalAccountPackage rentalAccountPackage){
        return Result.OK("equ.disarming.success",equService.disarmingCar(rentalAccountPackage));
    }

    @PostMapping("/defensive/manage/disarming")
    @ApiOperation("撤防(管理员)")
    public Result disarming(@RequestBody RentalManageCarReq rentalManageCar){
        return Result.OK("equ.disarming.success",equService.disarmingManageCar(rentalManageCar.getCarId()));
    }
    @PostMapping("/handleLockOpen")
    @ApiOperation("龙头锁开")
    public Result handleLockOpen(@RequestBody RentalAccountPackage rentalAccountPackage){
        return Result.OK("equ.lock.open.success",equService.handleLockOpen(rentalAccountPackage));
    }

    @PostMapping("/handleLockClose")
    @ApiOperation("龙头锁关")
    public Result handleLockClose(@RequestBody RentalAccountPackage rentalAccountPackage){
        return Result.OK("equ.lock.close.success",equService.handleLockClose(rentalAccountPackage));
    }

    @PostMapping("/car/manage/handleLockOpen")
    @ApiOperation("龙头锁(管理员)")
    public Result handleLockOpenManage(@RequestBody RentalManageCarReq rentalManageCar){
        return Result.OK("equ.defense.success",equService.handleManageLockOpen(rentalManageCar.getCarId()));
    }

    @PostMapping("/car/manage/handleLockClose")
    @ApiOperation("龙头锁关(管理员)")
    public Result handleLockCloseManage(@RequestBody RentalManageCarReq rentalManageCar){
        return Result.OK("equ.lock.close.success",equService.handleManageLockClose(rentalManageCar.getCarId()));
    }


    @PostMapping("/car/manage/setSpeedLimit")
    @ApiOperation("设置限速(管理员)")
    public Result setSpeedLimit(@RequestBody RentalManageCarReq rentalManageCar){
        return Result.OK("equ.lock.close.success",equService.setSpeedLimit(rentalManageCar.getCarId(),rentalManageCar.getSpeedLimitEnabled()));
    }
    @PostMapping("/car/pairRemoteControl")
    @ApiOperation("遥控器配对")
    public Result pairRemoteControl(@RequestBody RentalManageCarReq rentalManageCar) {
        try {
            boolean isPaired = equService.pairRemoteControl(rentalManageCar.getCarId());
            if (isPaired) {
                return Result.OK("遥控器配对成功");
            } else {
                return Result.error("遥控器配对失败");
            }
        } catch (Exception e) {
            log.error("遥控器配对失败", e);
            return Result.error("遥控器配对失败：" + e.getMessage());
        }
    }
    @PostMapping("/car/clearRemoteControl")
    @ApiOperation("清空遥控器")
    public Result clearRemoteControl(@RequestBody RentalManageCarReq rentalManageCar) {
        try {
            boolean isCleared = equService.clearRemoteControl(rentalManageCar.getCarId());
            if (isCleared) {
                return Result.OK("清空遥控器成功");
            } else {
                return Result.error("清空遥控器失败");
            }
        } catch (Exception e) {
            log.error("清空遥控器失败", e);
            return Result.error("清空遥控器失败：" + e.getMessage());
        }
    }

    @PostMapping("/searchCar")
    @ApiOperation("寻车")
    public Result searchCar(@RequestBody RentalAccountPackage rentalAccountPackage){
        return Result.OK(equService.searchCar(rentalAccountPackage));
    }
    @PostMapping("/manage/searchCar")
        @ApiOperation("寻车")
        public Result searchManageCar(@RequestBody RentalManageCarReq rentalManageCar){
        return Result.OK(equService.searchManageCar(rentalManageCar.getCarId()));
    }

    @PostMapping("/seatLock")
        @ApiOperation("座位锁")
        public Result seatLock(@RequestBody RentalAccountPackage rentalAccountPackage){
        return Result.OK(equService.seatLock(rentalAccountPackage));
    }

    @PostMapping("/manage/seatLock")
    @ApiOperation("座位锁")
    public Result seatManageLock(@RequestBody RentalManageCarReq rentalManageCar){
        return Result.OK(equService.seatManageLock(rentalManageCar.getCarId()));
    }

    @GetMapping("/queryLocation")
    @ApiOperation("查询位置")
    public Result queryLocation(@RequestParam(name = "terminalId") String terminalId, @RequestParam(name = "phone") String phone) {
        try {
            // 创建测试数据



           /* byte[] data = new byte[]{(byte)0x48, (byte)0x57, (byte)0x5F, (byte)0x31, (byte)0x2E,(byte) 0x30,(byte) 0x00, (byte)0x00   };
             CanFrame canFrame = new  CanFrame(0x18FF21F4, 0x00FF21, data);

            // 获取处理器并处理消息
            PgnProcessor processor = (PgnProcessor) canMessageManager.getProcessorByPgn(canFrame.pgn);
            processor.process(canFrame );*/
            RentalEBike car = new RentalEBike();
            car.setPhone(phone);
            car.setCarCode(terminalId);

            // 调用service层的查询位置方法
            return equService.queryLocation(car);
        } catch (Exception e) {
            return Result.error("查询位置失败：" + e.getMessage());
        }
    }

    @GetMapping("/startLocationTrack")
    @ApiOperation("查询位置")
    public Boolean startLocationTrack(@RequestParam(name = "terminalId") String terminalId, @RequestParam(name = "phone") String phone, @RequestParam(name = "timeInterval") Short timeInterval, @RequestParam(name = "validityPeriod") int validityPeriod) {
        try {
            RentalEBike car = new RentalEBike();
            car.setPhone(phone);
            car.setCarCode(terminalId);

            // 调用service层的查询位置方法
            return iControlAPI.startLocationTrack(car.getCarCode(),car.getPhone(), timeInterval, validityPeriod);
        } catch (Exception e) {
            return Result.error("查询位置失败：" + e.getMessage()).isSuccess();
        }
    }

    @PostMapping("/queryLocation")
    @ApiOperation("查询位置")
    public Result queryLocation(@RequestBody RentalAccountPackage rentalAccountPackage) {
        try {

            // 调用service层的查询位置方法
            return equService.queryLocation(rentalAccountPackage);
        } catch (Exception e) {
            return Result.error("查询位置失败：" + e.getMessage());
        }
    }

    @GetMapping("/getFieldStatus")
    @ApiOperation("查询车辆 ACC 和车门锁状态")
    public Result<ObjectNode> getFieldStatus( @ApiParam(value = "设备ID", required = true) @RequestParam String carCode) {
        try {
            FieldStatus fieldStatus = vehicleCache.getFieldStatus(carCode);

            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode objectNode = objectMapper.createObjectNode();

            if (fieldStatus != null) {
                objectNode.put("acc", fieldStatus.isAcc());
                objectNode.put("doorLocked", fieldStatus.isDoorLocked());
            } else {
                // 处理 fieldStatus 为 null 的情况，例如：
                objectNode.put("acc", false); //  设置默认值
                objectNode.put("doorLocked", false); // 设置默认值
                // 或者返回错误信息： return Result.error("未找到该车辆的状态信息");
            }
            return Result.OK(objectNode); // 返回 ObjectNode

        } catch (Exception e) {
            log.error("查询车辆状态失败", e);
            return Result.error("查询车辆状态失败：" + e.getMessage());
        }
    }
    /* 控制器查询*/
  /*  @GetMapping("/queryControl")
    @ApiOperation("查询位置")
    public Result queryControl(@ApiParam(value = "address", required = true) @RequestParam String address) {
        try {

            // 调用service层的查询位置方法
            return equService.queryControl(address);
        } catch (Exception e) {
            return Result.error("查询位置失败：" + e.getMessage());
        }
    }*/


    @GetMapping("/ebike-status")
    @ApiOperation("查询车辆ACC和车门锁状态")
    public Result<ObjectNode> ebikeStatus( @ApiParam(value = "设备ID", required = true) @RequestParam String code) {
        try {

            RentalEBike rentalCar = rentalCarMapper.selectOne(new QueryWrapper<RentalEBike>().eq("code", code));

            FieldStatus fieldStatus = vehicleCache.getFieldStatus(rentalCar.getCarCode());
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode objectNode = objectMapper.createObjectNode();

            if (fieldStatus != null) {
                objectNode.put("acc", fieldStatus.isAcc());
                objectNode.put("doorLocked", fieldStatus.isDoorLocked());
            } else {
                // 处理 fieldStatus 为 null 的情况，例如：
                objectNode.put("acc", false); //  设置默认值
                objectNode.put("doorLocked", false); // 设置默认值
                // 或者返回错误信息： return Result.error("未找到该车辆的状态信息");
            }
            return Result.OK(objectNode); // 返回 ObjectNode

        } catch (Exception e) {
            log.error("查询车辆状态失败", e);
            return Result.error("查询车辆状态失败：" + e.getMessage());
        }
    }

    @PostMapping("/manage/queryLocation")
    @ApiOperation("查询位置(管理员)")
    public Result queryManageLocation(@RequestBody RentalManageCarReq rentalManageCar) {
        try {
            // 调用service层的查询位置方法
            return equService.queryLocation(rentalManageCar.getCarId());
        } catch (Exception e) {
            return Result.error("查询位置失败：" + e.getMessage());
        }
    }

    @PostMapping("/manage/setVolume")
    @ApiOperation("音量设置")
    public Result setVolume(@RequestBody RentalManageCarReq rentalManageCar){
        return Result.OK(equService.setVolume(rentalManageCar.getCarId(),rentalManageCar.getVolume()));
    }


    @PostMapping("/manage/setPlayAudio")
    @ApiOperation("音量选择")
    public Result setPlayAudio(@RequestBody RentalManageCarReq rentalManageCar){
        return Result.OK(equService.setPlayAudio(rentalManageCar.getCarId(),rentalManageCar.getAudioIndex()));
    }


    @GetMapping("/openPort")
    @ApiOperation("打开插座")
    public Result openPort(
            @RequestParam String deviceCode,
            @RequestParam int port,
            @RequestParam int time,
            @RequestParam(required=false, defaultValue="1000") int power,
            @RequestParam(required=false, defaultValue="1") int autoOpen,
            @RequestParam String openid) {
        try {

            return iControlAPI.openPort(deviceCode, port, time, power, autoOpen,openid);
        } catch (Exception e) {
            return Result.error("equ.port.open.fail",  e.getMessage());
        }
    }


    @GetMapping("/openManagePort")
    @ApiOperation("打开插座")
    public Result openManagePort(
            @RequestParam String deviceCode,
            @RequestParam int port,
            @RequestParam int time,
            @RequestParam(required=false, defaultValue="1000") int power,
            @RequestParam(required=false, defaultValue="1") int autoOpen) {
        try {

            return iControlAPI.openManagePort(deviceCode, port, time, power, autoOpen);
        } catch (Exception e) {
            return Result.error("equ.port.open.fail" ,e.getMessage());
        }
    }

    /**
     * 关闭指定端口
     * @param deviceCode 设备代码
     * @param port 端口号
     * @return 操作结果
     */
    @GetMapping("/closePort")
    @ApiOperation("关掉插座")
    public Result closePort(
            @RequestParam String deviceCode,
            @RequestParam int port) {

        try {
            iControlAPI.closePort(deviceCode, port);
            return Result.ok("关闭端口成功，序列号：" );
        } catch (Exception e) {
            return Result.error("equ.port.close.fail" , e.getMessage());
        }
    }


    @GetMapping("/closeManagePort")
    @ApiOperation("关掉插座")
    public Result closeManagePort(
            @RequestParam String deviceCode,
            @RequestParam int port) {

        try {

            return  iControlAPI.closeManagePort(deviceCode, port);
        } catch (Exception e) {
            return Result.error("equ.port.close.fail" , e.getMessage());
        }
    }

    @GetMapping("/queryPort")
    @ApiOperation("查询插座")
    public Result queryPort(
            @RequestParam String deviceCode) {

        try {
            Integer seq = iControlAPI.queryPort(deviceCode);
            return Result.ok("查询插座成功，序列号：" + seq);
        } catch (Exception e) {
            return Result.error("查询插座失败：" + e.getMessage());
        }
    }

    /*查询电池*/


    @GetMapping("/setPower")
    @ApiOperation("设置电池")
    public Result setPower(@RequestParam(name = "terminalId") String terminalId) {

        try {
            RentalEBike car=new RentalEBike();
            String pohone="";
            if (terminalId.length() > 3) {
                pohone = terminalId.substring(3);
            } else {
                pohone = terminalId; // 或者根据需要处理，例如保留原字符串
            }

            car.setPhone(pohone);
            car.setCarCode( terminalId);
            Integer seq= iControlAPI.setPower(car.getCarCode(),car.getPhone(),true,1,20);

            return Result.ok("设置电池成功，序列号：" + seq);
        } catch (Exception e) {
            return Result.error("设置电池失败：" + e.getMessage());
        }
    }
    @GetMapping("/queryPower")
    @ApiOperation("查询电池")
    public Result queryPower(@RequestParam(name = "terminalId") String terminalId,@RequestParam(name = "phone") String phone) {

        try {
            RentalEBike car=new RentalEBike();
            car.setCarCode( terminalId);
            car.setPhone( phone);
            Integer seq = iControlAPI.queryPower(car.getCarCode(),car.getPhone());
            return Result.ok("查询电池成功，序列号：" );
        } catch (Exception e) {
            return Result.error("查询电池失败：" + e.getMessage());
        }
    }


    @GetMapping("/setSpeed")
    @ApiOperation("设置车速")
    public Result setSpeed(@RequestParam(name = "terminalId") String terminalId) {

        try {
            RentalEBike car=new RentalEBike();
            String pohone="";
            if (terminalId.length() > 3) {
                pohone = terminalId.substring(3);
            } else {
                pohone = terminalId; // 或者根据需要处理，例如保留原字符串
            }

            car.setPhone(pohone);
            car.setCarCode( terminalId);
            SpeedOtherConfig speedOtherConfig=new SpeedOtherConfig();
              iControlAPI.setSpeed(car.getCarCode(),car.getPhone(),speedOtherConfig);

            return Result.ok("设置车速成功，序列号："  );
        } catch (Exception e) {
            return Result.error("设置车速失败：" + e.getMessage());
        }
    }



    @GetMapping("/queryControl")
    @ApiOperation("查询控制器")
    public Result queryControl(@RequestParam(name = "terminalId") String terminalId,@RequestParam(name = "phone") String phone) {
        try {
            RentalEBike car=new RentalEBike();
            car.setPhone(phone);
            car.setCarCode( terminalId);
            //String mqttJson= controlService.queryControl(car);
            String mqttJson= iControlAPI.queryControl(car.getCarCode(),car.getPhone());
            //Integer seq = powerService.queryPower(car);
            System.out.println("查询控制器成功:" + mqttJson);
            // 创建一个线程来执行定时任务
           /* Thread thread = new Thread(() -> {
                while (true) {
                    try {

                        Thread.sleep(3000); // 每隔 3 秒执行一次
                    } catch (Exception e) {
                        System.out.println("查询控制器失败：" + e.getMessage());
                    }
                }
            });
            thread.start();*/

            return Result.ok("查询控制器");
        } catch (Exception e) {
            return Result.error("查询控制器失败：" + e.getMessage());
        }
    }

    @GetMapping("/setCentralControl")
    @ApiOperation("中控配置控制器")
    public Result setCentralControlConfig( @RequestParam(name = "terminalId") String terminalId) {

        try {
            RentalEBike car=new RentalEBike();
            String pohone="";
            if (terminalId.length() > 3) {
                pohone = terminalId.substring(3);
            } else {
                pohone = terminalId; // 或者根据需要处理，例如保留原字符串
            }

            car.setPhone(pohone);
            car.setCarCode( terminalId);
            CentralControlConfig config=new CentralControlConfig();
              iControlAPI.setCentralControlConfig(car.getCarCode(),car.getPhone(),config);

            return Result.ok("设置中控配置控制器成功，序列号："  );
        } catch (Exception e) {
            return Result.error("设置中控配置控制器失败：" + e.getMessage());
        }
    }


//    @GetMapping("/cabinet/list")
//    @ApiOperation("根据网点获取充电柜信息列表")
//    public Result<List<MapCabinetListRsp>> mapListCabinet(
//        @ApiParam(value = "网点id", name = "meshPointId") @RequestParam(value = "meshPointId",required = true) String meshPointId) throws InvocationTargetException, IllegalAccessException, InterruptedException, ExecutionException, TimeoutException {
//        log.info("根据网点获取充电柜信息列表",  meshPointId);
//        return    equService.mapListCabinet( meshPointId);
//    }

//    @GetMapping("/power/on")
//    @ApiOperation("用户取电操作")
//    public Result<ChargeElectricityConsumption> powerOn(
//            @ApiParam(value = "柜子id", name = "cabinetId") @RequestParam(value = "cabinetId",required = true) String cabinetId,
//            @ApiParam(value = "用户id", name = "accountId") @RequestParam(value = "accountId",required = true) String accountId) throws InterruptedException {
////        thingLock( accountId, cabinetId);
//        log.info("用户取电操作",  accountId,cabinetId);
//            return    equService.powerOn( accountId,cabinetId);
//    }
//
//
//    @GetMapping("/power/off")
//    @ApiOperation("用户退电操作")
//    public Result<ChargeElectricityConsumption> powerOff(
//            @ApiParam(value = "柜子id", name = "cabinetId") @RequestParam(value = "cabinetId",required = true) String cabinetId,
//            @ApiParam(value = "用户id", name = "accountId") @RequestParam(value = "accountId",required = true) String accountId) throws InterruptedException {
//        thingLock( accountId, cabinetId);
//        log.info("用户退电操作",  accountId,cabinetId);
//        return    equService.powerOff( accountId,cabinetId);
//    }
//
//
//    @GetMapping("/power/change")
//    @ApiOperation("用户换电操作")
//    public Result<ChargeElectricityConsumption> powerChange(
//            @ApiParam(value = "柜子id", name = "cabinetId") @RequestParam(value = "cabinetId",required = true) String cabinetId,
//            @ApiParam(value = "用户id", name = "accountId") @RequestParam(value = "accountId",required = true) String accountId) throws InterruptedException {
//        thingLock( accountId, cabinetId);
//        log.info("用户退电操作",  accountId,cabinetId);
//        return    equService.powerChange( accountId,cabinetId);
//    }
//
//    /**
//     * 分页列表查询
//     *
//     * @param cityId
//     * @param meshPointsName
//     * @return
//     */
//    @ApiOperation(value="城市网点列表查询", notes="城市网点列表查询")
//    @GetMapping(value = "/list/city")
//    public Result<List<ChargeMeshPoint>>chargeMeshByCity(@ApiParam(value = "城市编码", name = "cityId") @RequestParam(value = "cityId", required = true) String cityId,
//                                                              @ApiParam(value = "网点名称", name = "meshPointsName") @RequestParam(value = "meshPointsName", required = false) String meshPointsName) {
//        return equService.chargeMeshByCity(cityId,meshPointsName);
//    }
//
//    @GetMapping("/cabinet/warehouse/list")
//    @ApiOperation("获取柜子仓的信息列表")
//    public Result<List<CabinetWarehouseInfoRsp>> cabinetWarehouseInfo(
//            @ApiParam(value = "柜子id", name = "cabinetId") @RequestParam(value = "cabinetId",required = true) String cabinetId){
//
//        log.info("获取柜子仓的信息列表",  cabinetId);
//        return    equService.cabinetWarehouseInfo( cabinetId);
//    }


    public void thingLock(String accountId,String cabinetId){
        boolean flag = redissonLockClient.tryLock("OPERATION_CABINET" + cabinetId, 0, 60);
        if (flag) {
            throw new JeecgBootException("有人正在使用中请稍等!");
        }
        boolean flag1 = redissonLockClient.tryLock("ACCOUNTID_CABINET" + accountId, 0, 60);
        if (!flag1) {
            throw new JeecgBootException("common.too.frequent");
        }
    }

    @GetMapping("/unlock")
    public void unlock(
            @ApiParam(value = "柜子id", name = "cabinetId") @RequestParam(value = "cabinetId",required = true) String cabinetId,
        @ApiParam(value = "用户id", name = "accountId") @RequestParam(value = "accountId",required = true) String accountId) throws InterruptedException {
        redissonLockClient.unlock("OPERATION_CABINET" + cabinetId);
        redissonLockClient.unlock("ACCOUNTID_CABINET" + accountId);
    }



    @PostMapping("/moveCar")
    @ApiOperation("挪车")
    public Result moveCar(@RequestBody MoveCarReq moveCarReq) {
        try {
            // 调用 Service 中的挪车逻辑
            boolean isMoved = equService.moveCar(moveCarReq.getCarCode());

            if (isMoved) {
                return Result.OK("挪车成功");
            } else {
                return Result.error("挪车失败");
            }
        } catch (Exception e) {
            log.error("挪车失败", e);
            return Result.error("挪车失败：" + e.getMessage());
        }
    }
}
